<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form :model="queryData" layout="inline" size="small" v-if="permissionStore.hasPermisson('ssqywh.cx')">
            <a-form-item label="公司">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" v-model="queryData.firm"
                                    :loading="loading" :allowClear="true" :filter-option="false" @focus="focusSel">
                                    <a-option v-for="item in queryData.frimList">
                                        {{ item.typeName }}{{ item.typeName == "" ? "" : "-" }}{{ item.firmName }}
                                    </a-option>
                                </a-select> -->
              <a-cascader :options="pageData.corporateList" v-model="queryData.firmId" allow-clear class="bacClass"
                :loading="pageData.corporateLoading" popup-container="html"/>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="pageData.btnList" @select="selectHandler" @add="addHandler" @del="delWeipaichan"
            style="float: right">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>

      <!-- <div class="my-tool-bar">
                   
                </div> -->
    </template>
    <template #pageTabel>
      <!-- <a-tabs   :justify="true">
                    <a-tab-pane title="机器区域"> -->
      <!-- <a-table size="mini" style="height:100%" :scrollbar="true" sticky-header
                                 @page-change="pagination.change" stripe
                                 :bordered="true" :columns="columns"
                                 @change="handleChange"  :draggable="{type:'handle',width:20,fixed:true}"
                                 :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                                 v-model:selected-keys="selectedRowKeys" :loading="table.tableLoading"
                                 :data="table.dataList"
                                 :pagination="false"
                                 :rowKey="rowKey" :scroll="{x:'100%',y:'100%' ,maxHeight:'100%'}">
                            <template #obsoleteState="{ record }">
                                <a-space size="large">
                                    <a-switch checked-color="#F53F3F" unchecked-color="#14C9C9"
                                              v-model="record.obsoleteState" :checked-value="1" :unchecked-value="0"
                                              disabled>
                                        <template #checked>
                                            停用
                                        </template>
                                        <template #unchecked>
                                            启用
                                        </template>
                                    </a-switch>
                                </a-space>
                            </template>
                            <template #edit="{ record }">
                                <a-button type="primary" size="mini" status="warning" @click="editHandler(record)">
                                    <template #icon>
                                        <icon-edit/>
                                    </template>
                                    修 改
                                </a-button>
                            </template>
                        </a-table> -->
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" rowSelection="multiple" @grid-ready="gridReady" :suppressDragLeaveHidesColumns="true"
        @columnResized="onColumnResized" @columnMoved="onColumnMoved" @columnVisible="onColumnVisible"
        style="height: calc(100% - 45px);" :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList"
        :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
        <paginationCopys :page-size="pagination.pageSize" :current="pagination.page" :total="total" show-total show-jumper
      show-page-size @change="PageSize" @page-size-change="change1" style="justify-content: center" />
      <!-- </a-tab-pane>
                </a-tabs> -->
    </template>
    

    <a-drawer :style="{ zIndex: 999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd" unmountOnClose
      @ok="sideOk" @cancel="pageData.showAdd = false" cancel-text="关闭" ok-text="保存">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="formData" layout="horizontal">
          <a-form-item label-col-flex="80px" label="公司" field="firmId" :rules="[{ required: true, message: '公司必填' }]"
            :validate-trigger="['change', 'blur']">
            <!-- <a-select popup-container="html" 
                  class="bacClass"
                  placeholder=""
                  v-model="formData.firmId"
                  :loading="loading"
                  :allowClear="true"
                  :filter-option="false"
                >
                  <a-option v-for="item in pageData.frimList" :value="item.id">
                    {{ item.typeName }}{{ item.typeName == '' ? '' : '-' }}{{ item.firmName }}
                  </a-option>
                </a-select> -->
            <a-cascader :options="pageData.corporateList" @change="corporateChange" v-model="formData.firmId" allow-clear
              class="bacClass" ref="corporateRef" :loading="pageData.corporateLoading" popup-container="html"/>
          </a-form-item>
          <a-form-item label-col-flex="80px" field="areaName" label="区域名称"
            :rules="[{ required: true, message: '区域名称必填' }]" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" v-model="formData.areaName" placeholder="" />
          </a-form-item>
          <!-- <a-form-item label-col-flex="80px" label="备注"> -->
          <!-- <a-input class="bacClass" v-model="formData.remark" /> -->
          <!-- <a-textarea
                class="bacClass"
                placeholder=""
                v-model="formData.remark"
                :max-length="400"
                allow-clear
                show-word-limit
              />
            </a-form-item> -->
          <a-form-item label-col-flex="80px" label="是否停用" field="obsoleteState">
            <a-switch checked-color="#F53F3F" unchecked-color="#14C9C9" v-model="formData.obsoleteState"
              :checked-value="1" :unchecked-value="0" style="width: 65px">
              <template #checked> 停用 </template>
              <template #unchecked> 启用 </template>
            </a-switch>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>
  
<script setup lang="ts">
import { get, post } from '@/api/http'
import {
  usePagination,
  useRowKey,
  useRowSelection,
  useTable,
  useTableColumn,
} from '@/hooks/table'
import { onMounted, reactive, ref } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import WHService from '@/service/wh'

import { fail } from 'assert'
import { localeText } from '@/api/aggridZw'
import usePermission from '@/store/modules/permission'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
const whService = new WHService()
const companyList = whService.companyList
const localeText1: any = ref(localeText)
import { slicing } from '@/utils/caseFrimAndSecRig'
interface Cloth {
  code: string
}

interface MachineType {
  id: null
  firm: string
  name: string
  maxCapacity: number
  //删除
  deleteState: number
  // 作废的状态
  obsoleteState: number
  areaName: any
  remark: any
}

const rowKey = useRowKey('id')

interface gcTsObj {
  code: string
  company: string
  createDate: string
  createUser: string
  id: number
  isActive: boolean
  remark: string
  sortIndex: number
  updateDate: string
  updateUser: string
}
const corporateRef = ref<any>()
const corporateChange = (event: any) => {
  nextTick(() => {
    formData.firm = slicing(corporateRef.value.selectViewValue[0].label)
  })
}
// 获取公司列表
const getCorporateList = async () => {
  try {
    pageData.corporateLoading = true
    // const res = await post({ url: 'org/baCompany/getTreeCompanyByUser' })
    const res = await post({ url: 'org/baCompany/getTreeCompanyOrDepartment' })
    if (res.code == 200) {
      pageData.corporateList = res.data
      return
    }
    Message.error(res.message)
  } catch (error: any) {
    pageData.corporateLoading = false
  } finally {
    pageData.corporateLoading = false
  }
}
let gsDatas: any = ref([])
const total = ref(10)
const page = ref(1)
const size = ref(10)

function PageSize(val: any) {
  pagination.page = val
  doRefresh()
}

function change1(val: any) {
  pagination.pageSize = val
  doRefresh()
}

let gc = reactive<gcTsObj[]>([])
gc = JSON.parse(localStorage.getItem('gc') || '{}')
//查询表单form和select绑定的数据
const queryData: any = reactive({
  firm: '',
  gcList: [],
  frimList: [],
  firmId: '',
})

//机台类别form和select绑定的数据
const typeData = reactive({
  types: '',
})

//所属区域form和select绑定的数据
const areaData = reactive({
  areas: '',
})

//下拉框和弹窗的数据变量
const pageData = reactive<{
  //暂时，需要等后台返回的数据类型，再看定义ts
  frimList: []
  showAdd: boolean
  sideTitle: string
  corporateList: any[]
  corporateId: string
  corporateLoading: boolean
  btnList: any[]
}>({
  //弹窗是否显示
  showAdd: false,
  //弹窗的标题
  sideTitle: '新增类型',
  frimList: [],
  corporateList: [],
  corporateId: '',
  corporateLoading: false,
  btnList: [],
})

//修改
//record：是点击修改时，得到当前被点击项的对象数据

const headerShow = ref<boolean>(true)
const editHandler = (record: MachineType) => {
  //数据回填
  for (var key in record) {
    formData[key] = record[key]
  }
  // formData.obsoleteState = record.obsoleteState
  // formData.id = record.id
  // formData.firmId = record.firmId
  // formData.areaName = record.areaName
  // formData.remark = record.remark
  //显示弹窗
  pageData.showAdd = true
  //弹窗的标题
  pageData.sideTitle = '修改区域'
}

//表格的列描述信息|
const columns = useTableColumn([
  // {
  //   title: '序号',
  //   // 列信息的标识，对应表格的数据
  //   dataIndex: 'serialNo',
  //   key: 'serialNo',
  //   width: 150,
  // },
  {
    title: '公司',
    dataIndex: 'firm',
    width: 150,
    key: 'firm',
  },
  {
    title: '区域名称',
    dataIndex: 'areaName',
    width: 150,
    key: 'areaName',
  },

  {
    title: '启用/停用',
    key: 'obsoleteState',
    dataIndex: 'obsoleteState',
    slotName: 'obsoleteState',
    width: 150,
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    width: 200,
  },
  {
    title: '修改人',
    key: 'updateName',
    dataIndex: 'updateName',
    width: 150,
  },
  {
    title: '修改时间',
    key: 'updateTime',
    dataIndex: 'updateTime',
    width: 200,
  },
  {
    title: '备注',
    key: 'remark',
    dataIndex: 'remark',
    width: 150,
  },
  {
    title: '操作',
    key: 'edit',
    slotName: 'edit',
    dataIndex: 'edit',
    width: 150,
    fixed: 'right',
  },
])

let tc: any[] = columns.map((o) => {
  let obj = {
    headerName: o.title,
    field: o.key,
    pinned: o['fixed'],
    tooltipField: o.key,
  }
  if (o.slotName === 'obsoleteState') {
    // obj['resizable'] = false
    // obj['filter'] = false
    // obj['sortable'] = false
    // obj["lockPosition"]="right"
    obj['cellRenderer'] = {
      // template: `<a-switch checked-color="#F53F3F" unchecked-color="#14C9C9" :default-checked="a" :checked-value="1" :unchecked-value="0" disabled>
      //                 <template #checked>停用</template>
      //                 <template #unchecked>启用</template>
      //            </a-switch>`,
      // setup(props: any) {
      //     const a = ref()
      //     if(props.params.data.obsoleteState == "1"){
      //         a.value=true
      //     }else{
      //         a.value=false
      //     }
      //     // console.log(a.value,props.params.data.obsoleteState)
      //     return {
      //         a
      //     }
      // }

      //template: `<a-tag color="#f53f3f" v-if="params.data.obsoleteState==1">{{val}}</a-tag><a-tag color="green" v-else>{{val}}</a-tag>`,
      template: `<el-tag type="success" v-if="params.data.obsoleteState==1">{{val}}</el-tag><el-tag type="warning" v-else>{{val}}</el-tag>`,
      setup(props: any) {
        let val = ref()
        if (props.params.data.obsoleteState == 0) {
          val.value = '启用'
        } else {
          val.value = '停用'
        }

        return {
          val,
        }
      },
    }
    obj['filterParams'] = {
      valueFormatter: function (params: any) {
        return params.value == '0'
          ? '启用'
          : '停用'
      },
    }
  }
  if (o.slotName === 'edit') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['lockPosition'] = 'right'
    obj['width'] = '100px'
    obj['cellRenderer'] = {
      // template: `<a-tag color="#ff7d00" style="cursor:pointer" @click="a">修改</a-tag>`,
      template: `<a-tag class="tagCss" v-if="isEdit" @click="a">修改</a-tag>`,
      setup(props: any) {
        const a = () => {
          editHandler(props.params.data)
        }
        let isEdit = permissionStore.hasPermisson('ssqywh.xg')
        return {
          a,
          isEdit,
        }
      },
    }
  }

  return obj
})

let a = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
]
tc = a.concat(tc)

//新增修改弹窗动态绑定的数据
let formData: any = reactive({
  id: null,
  firmId: null,
  firm: '',
  areaName: '',
  obsoleteState: 0,
  remark: '',
})

onMounted(() => {
  updateGridState01()
  getCorporateList()
  // getAllFrim()
})

const focusSel = () => {
  // getAllFrim()
}
//获取所有公司
// function getAllFrim() {
//   //发请求 拿到公司的数据
//   post({
//     url: 'org/firmGroup/getFirmInfoByMap',
//     data: {
//       firmName: '',
//       department: '',
//     },
//   }).then((result) => {
//     if (result.code === 200) {
//       if (result.data.length == 0) {
//         Message.warning('暂无公司！')
//         pageData.frimList = []
//         queryData.frimList = []
//       } else {
//         pageData.frimList = result.data
//         queryData.frimList = result.data
//         pageData.frimList.forEach(function (o: any) {
//           Object.assign(o, { isClick: false })
//         })
//       }
//     } else {
//       Message.error(result.data.message)
//     }
//   })
// }

//复选框选中的值
const { selectedRowKeys } = useRowSelection()

//此方法用于表格数据动态渲染
const table = useTable()

//表格的pagination分页的属性配置
const pagination = usePagination(doRefresh)

function doRefresh() {
  //发起分页查询的请求
  post({
    url: 'planSingle/machineArea/getMachineAreaPage',
    data: {
      page: pagination.page,
      size: pagination.pageSize,
      firmId: queryData.firmId,
    },
  }).then((result: any) => {
    //如果后台返回的状态码为200才能执行后续操作
    if (result.code === 200) {
      //将后台返回的分页查询数据传入，这个方法可获取表格的数据dataList,动态渲染表格，表格的data属性动态绑定table.dataList即可实现动态渲染
      table.handleSuccess(result.data.list)
      //result.data.pages：总页数
      //使用这个方法，可以将pagination总页数pageCount改为-当前用户点击查询后台返回的总页数
      //传入完成之后，即可动态绑定表格渲染
      // pagination.setTotalSize(result.data.total);
      gridOption.value.setRowData(result.data.list)
      total.value = result.data.total
    }
  })
}

let cxbl = ''
//查询
const selectHandler = () => {
  pagination.page = 1
  cxbl = queryData.firm
  doRefresh()
}

function tableToXlsx(table: any, filename: any) {
  const uri = 'data:application/vnd.ms-excel;base64,',
    template = `<html>
              <head><meta charset="UTF-8"></head>
              <body><table border="1">${table.innerHTML}</table></body>
          </html>`

  const a = document.createElement('a')
  a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
  a.download = filename
  a.click()
  const EleDiv = document.getElementById('EleExport')
  EleDiv?.appendChild(a)
  EleDiv?.removeChild(a)
}

//导出
const print = () => {
  Modal.confirm({
    title: '系统提示',
    content: '是否导出列表数据',
    onOk() {
      let table = document.getElementsByTagName('table')[3]
      console.log(table)
      tableToXlsx(table, '所属区域维护')
    },
  })
}

// 表格准备事件
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}

//弹窗的确认和取消
const formRef = ref<FormInstance>()
const sideOk = () => {
  formRef.value?.validate().then((err) => {
    if (!err) {
      pageData.frimList.filter((res: any) => {
        if (formData.firmId == res.id) {
          formData.firm = res.typeName ? res.typeName + '-' + res.firmName : res.firmName
        }
      })
      if (pageData.sideTitle === '新增区域') {
        post({
          url: 'planSingle/machineArea/addMachineArea',
          data: [
            {
              firmId: formData.firmId,
              firm: formData.firm,
              areaName: formData.areaName,
              remark: formData.remark,
            },
          ],
        }).then((res: any) => {
          if (res.code === 200) {
            formRef.value?.resetFields()
            doRefresh()
            //提示
            Message.success('新增成功')
            //新增成功清空表单
            for (let item in formData) {
              formData[item] = ''
            }
            pageData.showAdd = false
          } else {
            Message.error(res.message)
          }
        })
      } else {
        post({
          url: 'planSingle/machineArea/updateMachineArea',
          data: [formData],
        }).then((res: any) => {
          if (res.code === 200) {
            formRef.value?.resetFields()
            doRefresh()
            Message.success('修改成功')
            //新增成功清空表单
            formData.id = null
            pageData.showAdd = false
          } else {
            Message.error(res.message)
          }
        })
      }
    }
  })
}
const sideNo = () => {
  pageData.showAdd = false

  formData.firm = ''
  formData.areaName = ''
}

//新增
const addHandler = () => {
  for (var key in formData) {
    if (key === 'id') {
      formData[key] = null
    } else if (key === 'deleteState' || key === 'donationMoney' || key === 'deleteDonation') {
      formData[key] = 0
    } else {
      formData[key] = ''
    }
  }
  pageData.showAdd = true
  pageData.sideTitle = '新增区域'
}

//生成条码
//暂时any,后续需要根据后台返回的数据进行类型定义
const GenerateBtn = (record: any) => {
  console.log(1)
}

//删除
const delWeipaichan = () => {
  // if (selectedRowKeys.value.length === 0) {
  //     Message.error('请先勾选')
  //     return
  // }
  if (gridOption.value.getSelectedRows() === 0) {
    Message.error('请先勾选')
    return
  }
  const isArray = selectedRowKeys.value.map((num) => {
    return Number(num)
  })

  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      //删除的请求
      post({
        url: 'planSingle/machineArea/delMachineArea',
        // data: isArray
        data: gridOption.value.getSelectedRows().map((o: any) => {
          return o.id
        }),
      }).then((res: any) => {
        console.log(res)
        if (res.code === 200) {
          Message.success({
            content: '删除成功',
            duration: 5000,
          })
          pagination.page = 1
          doRefresh()
        } else {
          Message.error({
            content: '删除失败',
            duration: 5000,
          })
        }
      })
    },
  })
}
const handleChange = (_data: any) => {
  table.handleSuccess(_data)
}
const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
  flex: 1
}
//:items="['查询', '新增', '删除']"
const permissionStore = usePermission()
if (permissionStore.hasPermisson('ssqywh.cx')) {
  pageData.btnList.push('查询')
}
if (permissionStore.hasPermisson('ssqywh.xz')) {
  pageData.btnList.push('新增')
}
if (permissionStore.hasPermisson('ssqywh.sc')) {
  pageData.btnList.push('删除')
}
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('RegionalMaintenance-1', gridOption, colState, tc)
const onColumnMoved = () => {
  saveGridState01()
}
const onColumnResized = () => {
  saveGridState01()
}
const onColumnVisible = () => {
  saveGridState01()
}
</script>
  
<style scoped lang="less">
.toolbar-item {
  cursor: pointer;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.ag-cell.ag-cell-first-right-pinned:not(.ag-cell-range-left):not(.ag-cell-range-single-cell)) {
  text-align: center;
}
</style>
  